#!/usr/bin/env node
const inquirer = require('inquirer')
const fs = require('fs')
const ora = require('ora')
const path = require('path');
const download = require('download-git-repo')
const templateList = require(`${__dirname}/../template`)
const symbols = require('log-symbols')
const chalk = require('chalk')
const spinner = ora(chalk.green('下载中...'));
chalk.level = 3
const cwd = process.cwd();
// 获取项目模板list
let list = [];
for (let key in templateList) {
    list.push(key)
}
let question = [
    {
        name: "projectTemplate",
        message: "请选择项目模板?",
        type: 'list',
        choices: list,
        validate(val) {

        }
    },
    {
        type: 'input',
        name: 'projectName',
        message: '请填写项目名称',
        validate(val) {
            if (!val) {
                return chalk.red('projectName is required!')
            } else {
                return true
            }
        }
    }
]

inquirer.prompt(question).then((answers) => {
    let { name, url } = answers;
    // 获取当前路径
    const targetDir = path.resolve(cwd, answers.projectName || '.');
    // 判断当前路径下是否有这个文件夹
    if (!fs.existsSync(targetDir)) {
        downloadGitRepo(answers);
    } else {
        console.log(chalk.bgRed('当前路径已存在同名目录，请确定后再试'));
    }
})
/**
 * 下载 git 仓库
 * @param {项目名} projectName
 */
function downloadGitRepo(answers) {
    const { projectTemplate, projectName } = answers;
    console.log(chalk.blue('正在拉取' + projectTemplate + '项目模板'));
    // 出现加载图标
    spinner.start();
    //git 上的地址
    let url = templateList[projectTemplate]
    download(
        `direct:${url}`,
        `./${projectName}`,
        { clone: true },
        function (err) {
            if (err) {
                // 下载失败
                spinner.fail(chalk.bgRed('下载失败'));
            } else {
                // 下载成功
                // 获取当前路径
                // 结束加载图标
                spinner.succeed(chalk.bgGreen('下载成功'));
                console.log('\n To get started')
                console.log(`\n    cd ${projectName} \n`)
            }
        }
    );
   
}